package shaka.ui

import shaka.db.DbEngine
import shaka.groovy.db.DbGryTools

public class FuncStorage {
	private static final FuncStorage instance = new FuncStorage()
	private FuncStorage(){
	}
	public FuncStorage getInstance(){
		return instance
	}

	public void tableInit(){
		File f = new File('./storage')
		if(!f.exists())
			f.mkdir()

		DbGryTools.withTransaction {
			DbEngine db = DbEngine.instance
			db.update("""
			create table if not exists func_storage (
				fn_name varchar(20),
				key     varchar(50),
				value   text,
				sort    number(10),
				primary key (fn_name, key)
			)
			""")
		}
	}

	public void func(String fn_name, String key, String value){
		DbGryTools.withTransaction {
			DbEngine db = DbEngine.instance
			db.pSql("select count(*) CNT from func_storage where fn_name = ? and key = ?")
			int cnt = db.pQuery([String, String] as Class[], [fn_name, key] as Object[])[0]['CNT']
			if(cnt == 0){
				// insert
				db.pSql("select count(*) cnt from func_storage where fn_name = ?")
				int sort = db.pQuery([String] as Class[], [fn_name] as Object[])[0]['cnt']
				db.pSql("insert into func_storage values (?, ?, ?, ?)")
				db.pUpdate([String, String, String, int] as Class[], [fn_name, key, value, sort + 1] as Object[])
			}else{
				// update
				db.pSql("update func_storage set value = ? where fn_name = ? and key = ?")
				db.pUpdate([String, String, String] as Class[], [value, fn_name, key] as Object[])
			}
		}
	}

	public String func(String fn_name, String key){
		DbGryTools.withNoTransaction {
			DbEngine db = DbEngine.instance
			db.pSql("select value from func_storage where fn_name = ? and key = ?")
			return db.pQuery([String, String] as Class[], [fn_name, key] as Object[])[0]['value']
		}
	}

	public List<Map<String, Object>> funcs(String fn_name){
		DbGryTools.withNoTransaction {
			DbEngine db = DbEngine.instance
			db.pSql("select fn_name, key, value, sort from func_storage where fn_name = ? order by sort")
			return db.pQuery([String] as Class[], [fn_name] as Object[])
		}
	}

	public void rename(String fn_name, String key, String newKey){
		DbGryTools.withTransaction {
			DbEngine db = DbEngine.instance
			db.pSql("update func_storage set key = ? where fn_name = ? and key = ?")
			db.pUpdate([String, String, String] as Class[], [newKey, fn_name, key] as Object[])
		}
	}

	public void delete(String fn_name, String key){
		DbGryTools.withTransaction {
			DbEngine db = DbEngine.instance
			db.pSql("delete from func_storage where fn_name = ? and key = ?")
			db.pUpdate([String, String] as Class[], [fn_name, key] as Object[])
		}
	}
}
